package cn.com.chanyue.module;

import java.util.Date;

import org.apache.commons.lang3.StringUtils;
import org.nutz.dao.Dao;
import org.nutz.dao.Sqls;
import org.nutz.dao.sql.Sql;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.mvc.Mvcs;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.GET;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.annotation.Param;

import cn.com.chanyue.bean.Logs;
import cn.com.chanyue.bean.Urls;
import cn.com.chanyue.tool.CodeCryption;
import cn.com.chanyue.tool.ToolUtility;

/**
 * 
 * @author Howe
 * 
 */
@IocBean(fields = { "dao" })
public class ControlModule {

	private Dao dao;

	private final static String URL = "http://91c.net/";
	private final static String KEY = "1E05F045ED4FB9E99F93C513A9B47165";

	/**
	 * 短网址访问
	 * 
	 * @param key
	 * @return
	 */
	@GET
	@At("/*")
	@Ok("redirect:${obj}")
	public String redirect(String key) {

		if (!StringUtils.isBlank(key)) {

			Sql sql = Sqls
					.create("SELECT T.* FROM tb_chanyue_url_urls T WHERE T.SHORTKEY = @KEY");
			sql.params().set("KEY", key);
			sql.setCallback(Sqls.callback.entities());
			sql.setEntity(dao.getEntity(Urls.class));
			dao.execute(sql);
			Urls url = sql.getObject(Urls.class);
			if (url != null) {

				Logs log = new Logs();
				log.setReferer(StringUtils.isBlank(Mvcs.getReq().getHeader(
						"Referer")) ? "Direct" : Mvcs.getReq().getHeader(
						"Referer"));
				log.setShortKey(key);
				log.setAccessAgent(Mvcs.getReq().getHeader("User-Agent"));
				log.setAccessTime(new Date());
				log.setAccessIp(ToolUtility.getIpAddr(Mvcs.getReq()));
				dao.insert(log);
				return url.getLongUrl();
			} else
				return "http://www.91085.com/";
		} else
			return "http://www.91085.com/";
	}

	/**
	 * 网址缩短
	 * 
	 * @param token
	 * @param url
	 * @param key
	 * @return
	 */
	@Ok("raw")
	@At("/api/short")
	public String shortlUrl(@Param("token") String token,
			@Param("url") String url, @Param("key") String key) {

		try {

			url = CodeCryption.decode("URL", url);
			if (!StringUtils.isBlank(token) && token.equals(CodeCryption.encode("MD5", url + KEY))
					&& !StringUtils.isBlank(url) && ToolUtility.verifyUrl(url)) {

				if (!StringUtils.isBlank(key)) {

					Sql sql = Sqls
							.create("SELECT T.* FROM tb_chanyue_url_urls T WHERE T.SHORTKEY = @KEY");
					sql.params().set("KEY", key);
					sql.setCallback(Sqls.callback.entities());
					sql.setEntity(dao.getEntity(Urls.class));
					dao.execute(sql);
					Urls urls = sql.getObject(Urls.class);
					if (urls != null) {
						sql = Sqls
								.create("UPDATE tb_chanyue_url_urls SET LONGURL = @LONGURL, TITLE = @TITLE, "
										+ "ADDTIME = NOW() WHERE SHORTKEY = @SHORTKEY");
						sql.params().set("LONGURL", url).set("SHORTKEY", key)
								.set("TITLE", ToolUtility.getUrlTitle(url));
						dao.execute(sql);
						return "{\"result\":true,\"shortUrl\":\"" + URL + key
								+ "\"}".toString();
					} else {
						sql = Sqls
								.create("INSERT INTO tb_chanyue_url_urls(SHORTKEY, TITLE, "
										+ "LONGURL, ADDTIME) VALUES(@SHORTKEY, @TITLE, @LONGURL, NOW())");
						sql.params().set("SHORTKEY", key)
								.set("TITLE", ToolUtility.getUrlTitle(url))
								.set("LONGURL", url);
						dao.execute(sql);
						return "{\"result\":true,\"shortUrl\":\"" + URL + key
								+ "\"}".toString();
					}

				} else {

					Sql sql = Sqls
							.create("SELECT T.* FROM tb_chanyue_url_urls T WHERE T.LONGURL = @URL");
					sql.params().set("URL", url);
					sql.setCallback(Sqls.callback.entities());
					sql.setEntity(dao.getEntity(Urls.class));
					dao.execute(sql);

					key = sql.getObject(Urls.class) == null ? null : sql
							.getObject(Urls.class).getShortKey();

					if (!StringUtils.isBlank(key))
						return "{\"result\":true,\"shortUrl\":\"" + URL + key
								+ "\"}".toString();
					else {

						key = ToolUtility.ShortText(url)[0];
						sql = Sqls
								.create("INSERT INTO tb_chanyue_url_urls(SHORTKEY, TITLE, "
										+ "LONGURL, ADDTIME) VALUES(@SHORTKEY, @TITLE, @LONGURL, NOW())");
						sql.params().set("SHORTKEY", key)
								.set("TITLE", ToolUtility.getUrlTitle(url))
								.set("LONGURL", url);
						dao.execute(sql);

						return "{\"result\":true,\"shortUrl\":\"" + URL + key
								+ "\"}".toString();
					}

				}
			} else
				return "{\"result\":false,\"shortUrl\":null}".toString();
		} catch (Exception e) {
			return "{\"result\":false,\"shortUrl\":null}".toString();
		}
	}

	/**
	 * 短网址还原
	 * 
	 * @param token
	 * @param url
	 * @return
	 */
	@Ok("raw")
	@At("/api/long")
	public String longUrl(@Param("token") String token, @Param("url") String url) {

		url = CodeCryption.decode("URL", url);
		if (!StringUtils.isBlank(token) && token.equals(CodeCryption.encode("MD5", url + KEY))
				&& !StringUtils.isBlank(url) && ToolUtility.verifyUrl(url)
				&& url.indexOf(URL) >= 0) {
			Sql sql = Sqls
					.create("SELECT T.* FROM tb_chanyue_url_urls T WHERE T.SHORTKEY = @KEY");
			sql.params().set("KEY", url.replaceAll(URL, ""));
			sql.setCallback(Sqls.callback.entities());
			sql.setEntity(dao.getEntity(Urls.class));
			dao.execute(sql);
			Urls urls = sql.getObject(Urls.class);
			if (urls != null)
				return "{\"result\":true,\"longUrl\":\"" + urls.getLongUrl()
						+ "\"}".toString();
			else
				return "{\"result\":false,\"longUrl\":null}".toString();
		} else
			return "{\"result\":false,\"longUrl\":null}".toString();
	}

}